package MeteoCal.utility;

import MeteoCal.bean.ScheduleUserBean;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

/**
 *
 * @authors Guttadoro, Iommazzo, Saullo
 */ 
@FacesConverter(value="themeConverter")
public class ThemeConverter implements Converter {
    
    //@Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
                //ScheduleUserBean bean =  (ScheduleUserBean) fc.getExternalContext().getApplicationMap().get("scheduleUserBean");
        if(value != null && value.trim().length() > 0) {
            try{
                FacesContext context = FacesContext.getCurrentInstance();
                ScheduleUserBean bean = context.getApplication().evaluateExpressionGet(context, "#{scheduleUserBean}", ScheduleUserBean.class);
                System.err.println("Value " + value);
                List<Theme> list= bean.getThemes();
                for(Theme t: list){
                    System.err.println("Controllo" + t.getId());
                        if(t.getId().equals(value)){
                            System.err.println("Sto ritornando t --> " + t.getName());
                            //bean.setSelectedTheme(t);
                            return t;
                        }
                }
                System.err.println("Ritorno null");
            }
            catch(NumberFormatException e) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid user."));
            }
        }
        return null;
}

  //@Override
    public String getAsString(FacesContext fc, UIComponent uic, Object object) {
        if(object != null) {
            System.err.println("The object is NOT NULL.................................");
            return (((Theme) object).getId());
        }
        else {
             System.err.println("The object is  NULL.................................");
            return null;
        }
    }   
} 
